package com.ai.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;

/**
 * @Author jiaok
 * @Date 2024-08-01 10:00
 */
@Service
public class FileDownloadUtil {

    /**
     *
     * @param nginxImagesPath  nginx的存储位置
     * @param picturesUrl 图片的云端位置
     * @return 图片的本地存储位置
     * @throws IOException
     */
    public  String downloadImg(String nginxImagesPath,String picturesUrl) throws IOException {
        InputStream is = null;
        FileOutputStream fileOutputStream = null;
        try {
            //创建图片url
            URL url = new URL(picturesUrl);
            //        打开链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //        设置请求方式
            conn.setRequestMethod("GET");
            //        超时响应时间 10s
            conn.setConnectTimeout(10 * 1000);
            //        通过输入流获取图片数据
            is = conn.getInputStream();
            //        转换为二进制
            byte[] bytes = readInputStream(is);
            String filePath= new SimpleDateFormat("yyyyMMdd").format(new Date());

            String fileName =picturesUrl.substring(picturesUrl.lastIndexOf("/") + 1);

            //在指定位置创建文件
            String storagePath =  new String(nginxImagesPath + "/" + filePath + "/" + fileName);
            File file = new File(storagePath);
            //文件不存在
            if (!file.exists()) {
                //创建文件夹
                File dir = file.getParentFile();
                dir.mkdirs();//文件夹不存在，才会去创建
                file.createNewFile();
            }
            fileOutputStream = new FileOutputStream(file);
            //写入数据
            fileOutputStream.write(bytes);

            return storagePath;

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (null != is ){
                is.close();
            }
            if (null != fileOutputStream){
                fileOutputStream.close();
            }
        }

    }

    public static byte[] readInputStream(InputStream inStream) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        //创建一个Buffer字符串
        byte[] buffer = new byte[6024];
        //每次读取的字符串长度，如果为-1，代表全部读取完毕
        int len;
        //使用一个输入流从buffer里把数据读取出来
        while ((len = inStream.read(buffer)) != -1) {
            //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        //关闭输入流
        inStream.close();
        //把outStream里的数据写入内存
        return outStream.toByteArray();
    }
}
